#include "ZGifControl.h"
#include "ZTexture.h"
#include "ZRenderer.h"
#include "ZControlFactory.h"
#include "ZFileUtils.h"
#include "ZApplication.h"

namespace ZuiLib
{


	ZGifControl::ZGifControl(void)
		:m_curFrame(0),m_autoSize(false)
	{
	}


	ZGifControl::~ZGifControl(void)
	{
	}

	void ZGifControl::PaintStatusImage(ZRenderer* hDC)
	{
		if (m_texture)
		{
			ZRect rc;
			rc.SetSize(m_texture->GetSize());
			hDC->Draw(m_texture,m_rcItem,rc);
		}
	}


	void ZGifControl::SetFile(const char* file)
	{
		m_file=file;
		m_curFrame=0;

		m_gif=ZGif::Create();
		ZString path=ZFileUtils::Instance()->GetPathFromName(file);
		if (m_gif->LoadFromFile(path))
		{
			m_texture=GetRenerder()->CreateTexture(SDL_PIXELFORMAT_ABGR8888,SDL_TEXTUREACCESS_STREAMING,m_gif->GetWidth(),m_gif->GetHeight());
			m_texture->SetTextureBlendMode(SDL_BLENDMODE_BLEND);

			m_gif->ReadFrame(m_texture,m_curFrame);
			ScheduleOnce(schedule_selector(ZGifControl::UpdateFrame),m_gif->GetDurTime());
			if (m_autoSize)
			{
				SetFixedWidth(m_gif->GetWidth());
				SetFixedHeight(m_gif->GetHeight());
			}
			Invalidate();
		}

	}

	void ZGifControl::SetFileAsync(const char* file)
	{
		m_file=file;
		ZString path=ZFileUtils::Instance()->GetPathFromName(file);
		ZGif::LoadAsync(path,this,schedule_selector_gif(ZGifControl::OnLoadGif));
	}


	void ZGifControl::SetAutoSize(bool autoSize)
	{
		m_autoSize=autoSize;
	}

	void ZGifControl::UpdateFrame(int tick)
	{
		m_curFrame=(m_curFrame+1)%m_gif->GetFrameCount();
		m_gif->ReadFrame(m_texture,m_curFrame);
		ScheduleOnce(schedule_selector(ZGifControl::UpdateFrame),m_gif->GetDurTime());
		Invalidate();
	}

	void ZGifControl::OnLoadGif(ZGif* gif)
	{
		m_gif=gif;
		ZApplication::Instance()->PostSchedule(this,schedule_selector_void(ZGifControl::UpdateGif));
	}

	void ZGifControl::UpdateGif()
	{
		m_curFrame=0;
		m_texture=GetRenerder()->CreateTexture(SDL_PIXELFORMAT_ABGR8888,SDL_TEXTUREACCESS_STREAMING,m_gif->GetWidth(),m_gif->GetHeight());
		m_texture->SetTextureBlendMode(SDL_BLENDMODE_BLEND);

		m_gif->ReadFrame(m_texture,m_curFrame);
		ScheduleOnce(schedule_selector(ZGifControl::UpdateFrame),m_gif->GetDurTime());
		if (m_autoSize)
		{
			SetFixedWidth(m_gif->GetWidth());
			SetFixedHeight(m_gif->GetHeight());
		}
		Invalidate();
	}

	void ZGifControl::SetAttribute(const char* pstrName, const char* pstrValue)
	{
		if (strcmp(pstrName,"file")==0)
		{
			SetFile(pstrValue);
		}
		else if (strcmp(pstrName,"asyncfile")==0)
		{
			SetFileAsync(pstrValue);
		}
		else if (strcmp(pstrName,"autosize")==0)
		{
			SetAutoSize(strcmp(pstrValue,"true")==0);
		}
		else
			ZControl::SetAttribute(pstrName,pstrValue);
	}

	IMPL_ZCONTROL_FACTORY("GifControl",ZGifControl);

}
